package com.example.onlineeducation.ui.offline

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.text.Editable
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import com.bigkoo.pickerview.view.TimePickerView
import com.example.onlineeducation.App
import com.example.onlineeducation.BuildConfig
import com.example.onlineeducation.adapter.AddPictureAdapter
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.Constants
import com.example.onlineeducation.data.entity.OfflineExamDetailTranEntity
import com.example.onlineeducation.databinding.OfflineExamDetailActivityBinding
import com.example.onlineeducation.utils.NumTextWatcher
import com.example.onlineeducation.utils.DataUtils
import com.example.onlineeducation.utils.YcTimeUtils
import com.example.onlineeducation.utils.pictureseletor.YcFullyGridLayoutManager
import com.example.onlineeducation.utils.pictureseletor.YcPictureSelecorUtil
import com.example.onlineeducation.viewmodel.OfflineExamDetailVM
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.luck.picture.lib.tools.SdkVersionUtils
import com.yc.jetpacklib.download.YcDownload
import com.yc.jetpacklib.extension.*
import com.yc.jetpacklib.net.doFail
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.utils.YcTime
import com.yc.jetpacklib.utils.YcTime.dateToString
import com.yc.jetpacklib.widget.pickerview.YcPickerView
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.lang.ref.WeakReference
import java.math.BigDecimal
import java.util.*


/**
 * Creator: sindi
 * Date: 2022/4/1 15:10
 * UseDes:线下考试详情  备份
 */
@SuppressLint("SetTextI18n")
class OfflineExamDetailActivity : BaseActivity<OfflineExamDetailActivityBinding>(OfflineExamDetailActivityBinding::inflate) {
    private val mViewModel by ycViewModels<OfflineExamDetailVM>()
    private var selectList: MutableList<LocalMedia> = mutableListOf()
    private var mNewUploadImageNetUrls: MutableList<String> = mutableListOf()//新上传后的图片路径
    private val maxImages = 3
    private var mRecordId: String? = null//人员考试记录的id
    private var mPvTime: TimePickerView? = null
    private var mExamStartTime: String? = null
    private var mExamEndTime: String? = null
    private var mTotalScore: String = "0"

    companion object {
        private const val KEY_OFFLINE_EXAM_DETAIL_ENTITY = "key_offline_exam_detail_entity"

        @JvmStatic
        fun newInstance(context: Context, entity: OfflineExamDetailTranEntity, launcher: ActivityResultLauncher<Intent>) {
            val intent = Intent(context, OfflineExamDetailActivity::class.java).apply {
                putExtra(KEY_OFFLINE_EXAM_DETAIL_ENTITY, entity)
            }
            launcher.launch(intent)
        }

        @JvmStatic
        inline fun getLauncher(activity: ComponentActivity, crossinline block: () -> Unit): ActivityResultLauncher<Intent> {
            return activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == RESULT_OK) {
                    block.invoke()
                }
            }
        }
    }

    private val mAdapter by lazy {
        AddPictureAdapter(this@OfflineExamDetailActivity, maxImages).apply {
            itemClick = { position, _ ->
                YcPictureSelecorUtil.previewPicture(this@OfflineExamDetailActivity, position, selectList)
            }
            addPictureClick = {
                YcPictureSelecorUtil.addMultiplePicture(this@OfflineExamDetailActivity, maxImages, selectList,
                    object : OnResultCallbackListener<LocalMedia> {
                        override fun onResult(result: MutableList<LocalMedia>?) {
                            if (result != null) {
                                addPicture(result)
                            }
                        }

                        override fun onCancel() {}
                    })
            }
            removeClick = { index ->
                mViewBinding.onRefreshSaveBtn()
            }
        }
    }


    private fun addPicture(result: MutableList<LocalMedia>) {
        val mAdapterWeakReference = WeakReference(mAdapter)
        selectList.clear()
        selectList.addAll(result)
        if (mAdapterWeakReference.get() != null) {
            mAdapterWeakReference.get()!!.setList(selectList)
            mAdapterWeakReference.get()!!.notifyDataSetChanged()
        }
        mViewBinding.onRefreshSaveBtn()
    }


    override fun OfflineExamDetailActivityBinding.initView() {
        intent.getParcelableExtra<OfflineExamDetailTranEntity>(KEY_OFFLINE_EXAM_DETAIL_ENTITY)?.apply {
            mRecordId = this.id
            mExamStartTime = this.examStartDate
            mExamEndTime = this.examEndDate
            tvName.text = this.userName
            tvGroupName.text = this.groupName
            tvWorkType.text = this.workType
            mTotalScore = this.totalScore
            tvExamScores.setText(this.examScores.ycToNoEmpty(""))
            tvExamDuration.setText(this.answerTime.ycToStringNoEmptyNoZero(""))
            tvExamDate.setText(this.examDate.ycToNoEmpty("请选择"))
            if (this.webPathList.ycIsNotEmpty()) {
                for (item in this.webPathList!!) {
                    if (item.webPath.ycIsNotEmpty()) {
                        val pictureName = item.webPath!!.replace(BuildConfig.base_url + "examLogOffline" + "/", "")
                        val localMedia = LocalMedia(Constants.imgPath(pictureName), 0, 0, "")
                        localMedia.androidQToPath = Constants.imgPath(pictureName)
                        selectList.add(localMedia)
                        downloadImg(item.webPath, pictureName)
                    }
                }
            }
        }
        actionBar.setTitle("考试详情")
        tvExamDate.setOnClickListener {
            if (mPvTime == null) {
                mPvTime = YcPickerView.setTimePicker(this@OfflineExamDetailActivity, YcPickerView.YearMonthDate) { date, _ ->
                    if (checkTime(YcTimeUtils.dateToDate(date))) {
                        tvExamDate.setText(dateToString(date))
                        onRefreshSaveBtn()
                    }
                }
            }
            hideSoftInput()
            mPvTime!!.show()
        }
        rvAddPictures.apply {
            layoutManager = YcFullyGridLayoutManager(this@OfflineExamDetailActivity, 2, GridLayoutManager.VERTICAL, false)
            adapter = mAdapter
            mAdapter.setList(selectList)
        }
        tvExamScores.addTextChangedListener(object : NumTextWatcher(tvExamScores) {
            override fun afterTextChanged(s: Editable) {
                super.afterTextChanged(s)
                onRefreshSaveBtn()
            }
        })

        tvExamDuration.addTextChangedListener(object : NumTextWatcher(tvExamDuration) {
            override fun afterTextChanged(s: Editable) {
                super.afterTextChanged(s)
                onRefreshSaveBtn()
            }
        })

        btnSubmit.setOnClickListener {
            if (canSubmit()) {
                if (mNewUploadImageNetUrls.ycIsEmpty()) {
                    uploadImageData()
                } else {
                    mViewModel.submitExamDetails(mRecordId!!, tvExamDuration.text.toString(), tvExamScores.text.toString(), tvExamDate.getText())
                }
            }
        }

        App.mInstant.mViewModel.mProInfoEntity.observe {
            tvProName.text = it!!.proName
        }
        mViewModel.apply {
            mUploadMultipleFileResult.observe { ycResult ->
                ycResult.doSuccess { entity ->
                    mNewUploadImageNetUrls.clear()
                    if (entity.ycIsNotEmpty()) {
                        mNewUploadImageNetUrls.addAll(entity!!)
                        mViewModel.submitExamDetails(
                            mRecordId!!,
                            tvExamDuration.text.toString(),
                            tvExamScores.text.toString(),
                            tvExamDate.getText(),
                            DataUtils.listToStr(mNewUploadImageNetUrls)
                        )
                    } else {
                        showToast("提交失败")
                    }
                }.doFail {
                    //图片上传失败
                    mNewUploadImageNetUrls.clear()
                    showToast("提交失败")
                }
            }
            mSubmitExamDetailsResult.observe {
                it.doSuccess {
                    showToast("提交成功")
                    setResult(RESULT_OK)
                    finish()
                }.ycShowNetError()
            }
        }
    }

    private fun OfflineExamDetailActivityBinding.downloadImg(imageUrl: String, pictureName: String) {
        YcDownload.createDownloadApkHasProgress(this@OfflineExamDetailActivity, imageUrl, Constants.imgPath(pictureName), onSuccess = {
            //ImageLoadUtils.photoAlbumRefresh(this@OfflineExamDetailActivity, pictureName, Constants.imgPath(pictureName))//图片下载完成后，通知相册刷新
            mAdapter.setList(selectList)
            mAdapter.notifyDataSetChanged()
            onRefreshSaveBtn()
        }, onFail = {
            if (!mDialog.isShowing)
                mDialog.setMsg(it.ycToNoEmpty("加载失败"))
                    .setLeftBtnText("跳过")
                    .setRightBtnText("重试")
                    .setSingleOnClick {
                        downloadImg(imageUrl, pictureName)
                    }.show()
        }).start()
    }


    private fun checkTime(date: Date?): Boolean {
        if (mExamStartTime.ycIsEmpty()) {
            showToast("考试开始时间为空,请联系管理员添加")
            return false
        }
        if (mExamEndTime.ycIsEmpty()) {
            showToast("考试结束时间为空,请联系管理员添加")
            return false
        }
        if (mExamStartTime.ycIsEmpty()) {
            showToast("考试开始时间为空,请联系管理员添加")
            return false
        }
        if (date == null) {
            showToast("所选择时间不为空")
            return false
        }
        if (date.before(YcTime.stringToDate(mExamStartTime!!))) {
            showToast("所选择时间不能在考试开始时间之前")
            return false
        }
        if (date.after(YcTime.stringToDate(mExamEndTime!!))) {
            showToast("所选择时间不能在考试结束时间之后")
            return false
        }
        return true
    }

    private fun uploadImageData() {
        val builder: MultipartBody.Builder = MultipartBody.Builder().setType(MultipartBody.FORM) //表单类型
        builder.addFormDataPart("biz", "examLogOffline")//存储文件的目录，后台让我写死
        var file: File
        for (i in selectList.indices) {
            file = if (selectList[i].compressPath.ycIsNotEmpty()) {
                File(if (SdkVersionUtils.checkedAndroid_Q()) selectList[i].androidQToPath else selectList[i].compressPath)
            } else {
                File(if (SdkVersionUtils.checkedAndroid_Q()) selectList[i].androidQToPath else selectList[i].path)
            }
            if (file.exists()) {
                builder.addFormDataPart("file", file.name, file.asRequestBody("multipart/form-data".toMediaTypeOrNull())) //添加图片数据，body创建的请求体
            }
        }
        val parts: List<MultipartBody.Part> = builder.build().parts
        mViewModel.uploadMultipleFile(parts)
    }

    private fun OfflineExamDetailActivityBinding.onRefreshSaveBtn() {
        var isAble = true
        if (selectList.ycIsEmpty()) {
            isAble = false
        }
        if (tvExamScores.text.toString().ycIsEmpty()) {
            isAble = false
        }
        if (tvExamDuration.text.toString().ycIsEmpty()) {
            isAble = false
        }
        if (tvExamDate.getText().ycIsEmpty() || tvExamDate.getText() == "请选择" || tvExamDate.getText() == "") {
            isAble = false
        }
        btnSubmit.setIsBgAble(isAble)
    }

    private fun OfflineExamDetailActivityBinding.canSubmit(): Boolean {
        if (selectList.ycIsEmpty()) {
            showToast("请选择卷面图")
            return false
        }
        if (tvExamScores.text.toString().ycIsEmpty()) {
            showToast("请输入考试分数")
            return false
        }
        if (!DataUtils.checkStrIsNumTwo(tvExamScores.text.toString())) {
            showToast("请输入正确的考试分数")
            return false
        }
        if (BigDecimal(tvExamScores.text.toString()) > BigDecimal(mTotalScore)) {
            showToast("考试分数不能大于总分")
            return false
        }
        if (BigDecimal(tvExamScores.text.toString()) < BigDecimal.ZERO) {
            showToast("考试分数不能小于0分")
            return false
        }
        if (tvExamDuration.text.toString().ycIsEmpty()) {
            showToast("请输入考试时长")
            return false
        }

        if (!DataUtils.checkStrIsNumTwo(tvExamDuration.text.toString())) {
            showToast("请输入正确的考试时长")
            return false
        }
        if (BigDecimal(tvExamDuration.text.toString()) < BigDecimal.ZERO) {
            showToast("考试时长不能小于0分钟")
            return false
        }
        if (tvExamDate.getText().ycIsEmpty() || tvExamDate.getText() == "请选择") {
            showToast("请选择考试日期")
            return false
        }
        return true
    }

}